/**
 *
 *poi查询组件
 *
 *
 */
 POISearchWidget=OpenLayers.Class(BaseWidget,{
 	initialize : function() {
	},
	POILayer : null,//覆盖物图层
	popup : null,
	//返回组装好的地图切换控件dom对象
	getElement : function(){
		if(!this.element){
			if(this.config){
				//加载依赖的分页组件
				this.requireWidgetJs(this.config.jqPaginationJs);
				this.requireWidgetCSS(this.config.jqPaginationCss);
				this.element = this.createElement(this.map);
			}
		}
		return this.element;
	},
	createElement : function(){
		 var $this = this;
		 //添加图层
		 this.POILayer = new OpenLayers.Layer.Markers("markers");
		 this.POILayer.setZIndex(200);
         this.map.addLayer(this.POILayer);  
		  
		/*开始判断是否打开数据查询展示面板*/
		/*
		if($this.config.openResult){
			requireWidget();
		}
		*/
		var POISearchBox=$('<div id="POISearchWidget"></div>');
		if( this.config.top!=null)POISearchBox.css('top' ,this.config.top+'px');
		if( this.config.right!=null)POISearchBox.css('right' ,this.config.right+'px');
		if( this.config.left!=null)POISearchBox.css('left' ,this.config.left+'px');
		if( this.config.bottom!=null)POISearchBox.css('bottom' ,this.config.bottom+'px');
		POISearchBox.addClass('widget-class');
		POISearchBox.css({
			'width' :'300px',
			'height' : '153px'
		});
		var POIToolType=$('<div class="tabs" style="font-size:12px;">'+
		    '<ul>'+
		        '<li style="" class="poi"><a style="border:0px;" href="#tabs-1">热点查询</a></li>'+
		        '<li style="" class="dzbm"><a href="#tabs-2">地址编码</a></li>'+
		        '<li style="" class="fdzbm"><a href="#tabs-3">反向地址编码</a></li>'+
		    '</ul>'+
		    '<div id="tabs-1" style="padding-left:0px;padding-right:0px;padding-bottom:0px;height:100px;">'+
		        '<span>关键字：</span><input type="text"  class="key-name" name="poi"/><input type="button" class="dosearch" value="查询" name="poi"/>'+
		    '</div>'+
		    '<div id="tabs-2" style="padding-left:0px;padding-right:0px;padding-bottom:0px;height:100px;">'+
		        '<span>地址：</span><input type="text"  class="key-name" name="dzbm"/><input type="button" class="dosearch" value="查询" name="dzbm"/>'+
		    '</div>'+
		    '<div id="tabs-3" style="padding-left:0px;padding-right:0px;padding-bottom:0px;height:100px;">'+
		        '<span>坐标：</span><input type="text"  class="key-name" name="fdzbm"/><input type="button" class="dosearch" value="查询" name="fdzbm"/>'+
		    '</div>'+
		'</div>');
		
		POISearchBox.append(POIToolType);
		//添加关闭按钮
		var tabsClose=$('<div class="close"></div>');
		tabsClose.css({
			'width':'13px',
			'height':'16px',
			'position' : 'absolute',
			'right' :'5px',
			'margin-top' :'5px',
			'cursor' :'pointer',
			'background-image' : 'url(css/smoothness/images/ui-icons_888888_256x240.png)',
			'background-position' : '-82px -129px'
		}).mouseover(function(){
			$(this).css({
				'background-position' : '-33px -192px'
			});
		}).mouseout(function(){
			$(this).css({
				'background-position' : '-82px -129px'
			});
		}).click(function(){
			POISearchBox.animate({ width: 'toggle', opacity: 'toggle' },   "slow"); 
			POISearchBox.hide('slow');
		});
		POIToolType.find('ul').append(tabsClose);
		POIToolType.tabs();
		POISearchBox.find('input.key-name').css({
			'line-height' :'23px',
			'height' : '23px',
			'width' :'168',
			'margin-top' : '2px'
		}).keydown(function(e){
			if(e.keyCode==13){
				var name=$(this).attr('name');
				var keyword=POISearchBox.find('input.key-name').val();
				//poi查询接口
				if(name=='poi'){
					var config = {
						localProxyUrl : $this.config.localProxyUrl,
						ServerUrl : $this.config.poiServerUrl
					}
					$this.poiRequestData = {
						key : $this.config.key,
						batch : 1,
						city : $this.config.cityCode,
						encode : 'utf-8',
						keyword : keyword,
						number : 10,
						range : 3000,
						resType : "json",
						retvalue :1,
						rid :34462,
						sid : 1000,
						srctype : 'POI',
						type : ''
					};
					$this.POISearch(config,$this.poiRequestData);
				}else if(name=='dzbm'){
					keyword=$(POISearchBox.find('input.key-name')[1]).val();
					var config = {
						localProxyUrl : $this.config.localProxyUrl,
						ServerUrl : $this.config.geocodingServerUrl
					}
					var requestData = {
						address :keyword,//encodeURIComponent(encodeURIComponent(data.key))
						encode :'utf-8',
						key : $this.config.key,
						poinum : 2,
						range : 300,
						resType : "json",
						retvalue : 1,
						rid : 83908,
						sid : 7000
					};
					$this.GeocodingSearch(config,requestData);
				}else if(name=='fdzbm'){
					keyword=$(POISearchBox.find('input.key-name')[2]).val();
					var config = {
						localProxyUrl : $this.config.localProxyUrl,
						ServerUrl : $this.config.rgeocodeServerUrl
					}
					var requestData = {
						crossnum :2,
						encode : 'utf-8',
						key : $this.config.key,
						poinum : 2,
						range :300,
						region :keyword,
						resType :'json',
						retvalue :1,
						rid : 50325,
						roadnum :3,
						sid : 7001
					}
					
					$this.RgeocodeSearch(config,requestData);
				}
			}
				
		});
		POISearchBox.find('input.dosearch').css({
			'height' : '30px',
			'background-repeat' : 'no-repeat',
			'background-image' : 'url('+$this.config.searchIcon+')',
			'width' : '70px'
		}).click(function(){
				var name=$(this).attr('name');
				var keyword=POISearchBox.find('input.key-name').val();
				//poi查询接口
				if(name=='poi'){
					var config = {
						localProxyUrl : $this.config.localProxyUrl,
						ServerUrl : $this.config.poiServerUrl
					}
					$this.poiRequestData = {
						key : $this.config.key,
						batch : 1,
						city : $this.config.cityCode,
						encode : 'utf-8',
						keyword : keyword,
						number : 10,
						range : 3000,
						resType : "json",
						retvalue :1,
						rid :34462,
						sid : 1000,
						srctype : 'POI',
						type : ''
					};
					$this.POISearch(config,$this.poiRequestData);
				}else if(name=='dzbm'){
					keyword=$(POISearchBox.find('input.key-name')[1]).val();
					var config = {
						localProxyUrl : $this.config.localProxyUrl,
						ServerUrl : $this.config.geocodingServerUrl
					}
					var requestData = {
						address :keyword,//encodeURIComponent(encodeURIComponent(data.key))
						encode :'utf-8',
						key : $this.config.key,
						poinum : 2,
						range : 300,
						resType : "json",
						retvalue : 1,
						rid : 83908,
						sid : 7000
					};
					$this.GeocodingSearch(config,requestData);
				}else if(name=='fdzbm'){
					keyword=$(POISearchBox.find('input.key-name')[2]).val();
					var config = {
						localProxyUrl : $this.config.localProxyUrl,
						ServerUrl : $this.config.rgeocodeServerUrl
					}
					var requestData = {
						crossnum :2,
						encode : 'utf-8',
						key : $this.config.key,
						poinum : 2,
						range :300,
						region :keyword,
						resType :'json',
						retvalue :1,
						rid : 50325,
						roadnum :3,
						sid : 7001
					}
					
					$this.RgeocodeSearch(config,requestData);
				}
		});
		
		return POISearchBox;
	},
	POISearch : function(config,requestData,jqPagination){
			var $this = this;
			Interface.jsonRequest(config,requestData, function(response, config) {
					if($this.popup!=null){
                		$this.map.removePopup($this.popup);
			    		$this.popup.destroy();
			    		$this.popup = null;
		            }
					$this.POILayer.clearMarkers();
					var list = response.list;
					if(list==null)return;
					var bounds = new OpenLayers.Bounds();
					var remainder=(parseInt(response.count))%10;
					var max_page=0;
					var current_page=1;
					if(remainder==0){
						max_page=parseInt(response.count)/10;
					}else{
						max_page=parseInt(parseInt(response.count)/10)+1;
					}
					$("#ResultWidget .tabs-1 .rows").empty();
					var table=$('<table cellspacing="0" cellpadding="0"></table>');
					$("#ResultWidget .tabs-1 .rows").append(table);
					
					if($('#ResultWidget .tabs-1 .pagination').length==0){
						var pageBox=$(
						'<div class="pagination">'+
								  '<br><a href="#" class="first" data-action="first">&laquo;</a>'+
								  '<a href="#" class="previous" data-action="previous">&lsaquo;</a>'+
								  '<input type="text" readonly="readonly" data-max-page="40" />'+
								  '<a href="#" class="next" data-action="next">&rsaquo;</a>'+
								  '<a href="#" class="last" data-action="last">&raquo;</a>'+
							'</div>'
						);
						$("#ResultWidget .tabs-1 .page").append(pageBox);
						
						$('#ResultWidget .tabs-1 .pagination').jqPagination({
						  link_string : '/?page={page_number}',
						  current_page: current_page, //设置当前页 默认为1
						  max_page : max_page, //设置最大页 默认为1
						  page_string : '当前第{current_page}页,共{max_page}页',
						  paged : function(page) {
						      	var requestData=$this.poiRequestData;
						      	requestData.batch=page;
						      	var config = {
									localProxyUrl : $this.config.localProxyUrl,
									ServerUrl : $this.config.poiServerUrl
								}
						      	$this.POISearch(config,requestData,'jqPagination');
						     }
						});
						
					}else{
						if(jqPagination==null){
							$("#ResultWidget .tabs-1 .page").empty();
							var pageBox=$(
							'<div class="pagination">'+
									  '<br><a href="#" class="first" data-action="first">&laquo;</a>'+
									  '<a href="#" class="previous" data-action="previous">&lsaquo;</a>'+
									  '<input type="text" readonly="readonly" data-max-page="40" />'+
									  '<a href="#" class="next" data-action="next">&rsaquo;</a>'+
									  '<a href="#" class="last" data-action="last">&raquo;</a>'+
								'</div>'
							);
							$("#ResultWidget .tabs-1 .page").append(pageBox);
							var jqpage=$('#ResultWidget .tabs-1 .pagination').jqPagination({
							  link_string : '/?page={page_number}',
							  current_page: current_page, //设置当前页 默认为1
							  max_page : max_page, //设置最大页 默认为1
							  page_string : '当前第{current_page}页,共{max_page}页',
							  paged : function(page) {
							      	var requestData=$this.poiRequestData;
							      	requestData.batch=page;
							      	var config = {
										localProxyUrl : $this.config.localProxyUrl,
										ServerUrl : $this.config.poiServerUrl
									}
							      	$this.POISearch(config,requestData,'jqPagination');
							     }
							});
							//alert("current_page"+current_page);
							
						}
					}
					
					
					$.each(list, function(index, data) {
						var address=data.address;
						var name=data.name;
						var tel=data.tel;
						var x=data.x;
						var y=data.y;
						var lonlat=new OpenLayers.LonLat(x,y).transform($this.map.displayProjection,$this.map.getProjectionObject());
						bounds.extend(lonlat);
						var row=$("<tr>"+
									'<th style="width:31px;"><div clas="icon"></div></th>'+
									'<td style="width:190px;">'
										+"<div><span style='color:#0000CC;'>"+name+"<span></div>"
										+"<div style='color:black;'>地址：<span>"+address+"</span></div>"
										+"<div style='color:black;'>电话:<span>"+tel+"</span></div>"
									+'</td>'
								+'</tr>');
						table.append(row);
						var position='-'+index*24+'px -198px';
						row.find('th div').css({
							'width' :'19px',
							'height' :'25px',
							//'margin-top':'-23px',
							'background' :'url(images/custom/markers_new.png) no-repeat',
							'background-position' :position
						});
						
						
						
						var url = $this.config.icon;
						url='images/custom/markers/red/markers_new_'+(index+1)+'.png';
		                var sz = new OpenLayers.Size(22, 28);  //尺寸大小
		                var calculateOffset = function(size) {
		                    return new OpenLayers.Pixel(-(size.w/2), -size.h);
		                 };
		                var icon = new OpenLayers.Icon(url, sz, null, calculateOffset);
						var marker = new OpenLayers.Marker(lonlat, icon);
		                $this.POILayer.addMarker(marker);
		                marker.events.element.title=name;
		                marker.events.element.style.cursor='pointer';
		                
		                marker.events.register('mouseover', marker, function(evt) {
		                	marker.icon.setUrl('images/custom/markers/blue/markers_new_'+(index+1)+'.png');
		                });
		                marker.events.register('mouseout', marker, function(evt) {
		                	marker.icon.setUrl('images/custom/markers/red/markers_new_'+(index+1)+'.png');
		                });
		                
		                row.css({
							'height' :'80px',
							'border-bottom' :'1px solid #D0D0D0',
							'margin-top':'5px',
							'margin-left':'2px',
							'cursor':'pointer'
							
						}).mouseover(function(){
							$(this).css({
								'background-color':'#F0F0F0'
							});
							position='-'+index*24+'px -230px';
							row.find('th div').css({
								'background-position' :position
							});
							marker.icon.setUrl('images/custom/markers/blue/markers_new_'+(index+1)+'.png');
						}).mouseout(function(){
							$(this).css('background-color','white');
							position='-'+index*24+'px -198px';
							row.find('th div').css({
								'background-position' :position
							});
							marker.icon.setUrl('images/custom/markers/red/markers_new_'+(index+1)+'.png');
						}).click(function(){
							$this.map.setCenter(lonlat, 14);  //添加平移缩放工具条
						});
						var markerClick=null;
		                marker.events.register('mousedown', marker, function(evt) {
		                	/*
		                	if(markerClick!=null){
		                		marker.icon.setSize(new OpenLayers.Size(22, 28));
		                		markerClick.icon.setUrl('images/custom/markers/red/markers_new_'+(index+1)+'.png');
		                	}
		                	markerClick=marker;
		                	marker.icon.setSize(new OpenLayers.Size(30, 41));
		                	
		                	marker.icon.setUrl('images/custom/markers/big/'+(index+1)+'.png');
		                	*/
		                	if($this.popup!=null){
		                		$this.map.removePopup($this.popup);
					    		$this.popup.destroy();
					    		$this.popup = null;
		                	}
		                	var content="<div class='popup-container' style='width:270px;height:140px;font-size:12px;#666;'>"+
			                				"<div class='popup-header' style='font-size:14px;color:blue;'>"+name+"</div>"+
			                				"<div class='popup-body'>"+
			                					'<table width=100%;>'+
			                						'<tr><td style="width:40px;">地址：</td><td>'+address+'</td></tr>'+
			                						'<tr><td>电话：</td><td>'+tel+'</td></tr>'+
			                						'<tr><td></td><td></td></tr>'+
			                						'<tr><td></td><td></td></tr>'+
			                						'<tr><td></td><td></td></tr>'+
			                					'</table>'+
			                				"</div>"+
		                				"</div>";
		               	 	$this.popup = new OpenLayers.Popup.FramedCloud(
		               	 	   "chicken",
			                    lonlat,
			                    null,
			                    content,
			                    null,
			                    true,
			                    function(popup){
			                    	if($this.popup!=null){
				                		$this.map.removePopup($this.popup);
							    		$this.popup.destroy();
							    		$this.popup = null;
				                	}
			                    }
			              	 );
			               	$this.map.addPopup($this.popup);
		                	OpenLayers.Event.stop(evt); 
		                });
				});
				//进行bounds定位
				$this.map.zoomToExtent(bounds,null);
				//打开数据展示面板
				$("#ResultWidget").show();
			},true);
	},
	GeocodingSearch : function(config,requestData){
		var $this = this;
		Interface.jsonRequest(config,requestData, function(response, config) {
				   if($this.popup!=null){
                		$this.map.removePopup($this.popup);
			    		$this.popup.destroy();
			    		$this.popup = null;
		            }
					$this.POILayer.clearMarkers();
					var list = response.list;
					if(list==null)return;
					var bounds = new OpenLayers.Bounds();
					$.each(list, function(index, data) {
						var name=data.name;
						var x=data.x;
						var y=data.y;
						var lonlat=new OpenLayers.LonLat(x,y).transform($this.map.displayProjection,$this.map.getProjectionObject());
						bounds.extend(lonlat);
						var url = $this.config.icon;
		                var sz = new OpenLayers.Size(32, 32);  //尺寸大小
		                var calculateOffset = function(size) {
		                    return new OpenLayers.Pixel(-(size.w/2), -size.h);
		                 };
		                var icon = new OpenLayers.Icon(url, sz, null, calculateOffset);
						var marker = new OpenLayers.Marker(lonlat, icon);
		                $this.POILayer.addMarker(marker);
		                marker.events.element.title=name;
					
					});
				//进行bounds定位
				$this.map.zoomToExtent(bounds,null);
					
		},true);
	},
	RgeocodeSearch : function(config,requestData){
		var $this = this;
		Interface.jsonRequest(config,requestData, function(response, config) {
			 if($this.popup!=null){
                		$this.map.removePopup($this.popup);
			    		$this.popup.destroy();
			    		$this.popup = null;
		            }
					$this.POILayer.clearMarkers();
					var list = response.list;
					if(list==null)return;
					var crosslist=list[0].crosslist;
					var poilist=list[0].poilist;
					if(crosslist==null)return;
					$.each(crosslist, function(index, data) {
					
					});
					if(poilist==null)return;
					$.each(poilist, function(index, data) {
						var name=data.name;
						var address=data.address;
						var x=data.x;
						var y=data.y;
						var lonlat=new OpenLayers.LonLat(x,y).transform($this.map.displayProjection,$this.map.getProjectionObject());
						var url = $this.config.icon;
		                var sz = new OpenLayers.Size(32, 32);  //尺寸大小
		                var calculateOffset = function(size) {
		                    return new OpenLayers.Pixel(-(size.w/2), -size.h);
		                 };
		                var icon = new OpenLayers.Icon(url, sz, null, calculateOffset);
						var marker = new OpenLayers.Marker(lonlat, icon);
		                $this.POILayer.addMarker(marker);
		                marker.events.element.title=name;
					});
		},true);
	},
	/**
	 *请求加载JS文件 
	 * @param {Object} label
	 */	
	requireWidgetJs : function(label){
		var jsNode = document.createElement('script');
        jsNode.setAttribute('src', label);
        jsNode.setAttribute('type', 'text/javascript');
		document.getElementsByTagName('head')[0].appendChild(jsNode); 
		//有这种写法，试了下，可以用
		// $.getScript(label,function(){});	
	},
	requireWidgetCSS : function(css){
		var CSSNode = document.createElement('link');
        CSSNode.setAttribute('href', css);
        CSSNode.setAttribute('rel', 'stylesheet');
        CSSNode.setAttribute('type', 'text/css');
		document.getElementsByTagName('head')[0].appendChild(CSSNode); 
	},
	poiRequestData :null,//poi参数
	CLASS_NAME:"openGis.POISearchWidget"
 });